package com.sls.web.manager.action.game;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;

import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.execption.ManagerException;
import com.sls.web.manager.game.pojo.JpayAreaInfo;
import com.sls.web.manager.game.pojo.JpayGoodsInfo;
import com.sls.web.manager.game.service.JpayService;
import com.sls.web.manager.page.Pagination;

@InterceptorRefs({
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"text/plain,application/excel,application/vnd.ms-excel" }),
		@InterceptorRef(value = "defalutStackSet") })
public class JpayAction extends SuperAction {

	private static final long serialVersionUID = -296221544802401095L;
	@Resource(name = "jpayService")
	private JpayService jpayService;
	private JpayGoodsInfo jpayGoodsInfo;
	private JpayGoodsInfo jpayGoodsQuery;
	private JpayAreaInfo jpayAreaInfo;
	private JpayAreaInfo jpayAreaQuery;
	private Pagination<?> page;
	private String id;
	private String goodsId;
	private String goodsName;
	private String gameId;
	private String supplierId;
	private int priceRatio;
	private String userid;
	private String requestid;
	private String history;
	private JpayGoodsInfo orderInfo;
	private JpayGoodsInfo balanceInfo;
	private File productExcel;// 获取上传文件
	private String productExcelFileName;// 获取上传文件名称
	private String productExcelContentType;// 获取上传文件类型

	public String add() {
		return INPUT;
	}

	/**
	 * 保存产品信息
	 * 
	 * @return
	 */
	public String save() {
		try {
			this.jpayService.saveGoods(jpayGoodsInfo, getCurrentOperator());
			this.redirectionUrl = "jpay!list.htm";
		} catch (ManagerException e) {
			flag = false;
			this.addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 列表展示
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		if (jpayGoodsQuery == null) {
			jpayGoodsQuery = new JpayGoodsInfo();
			jpayGoodsQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			jpayGoodsQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.jpayService.queryPage(jpayGoodsQuery,
					getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return LIST;
	}

	/**
	 * 区域列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public String areaList() throws Exception {
		if (jpayAreaQuery == null) {
			jpayAreaQuery = new JpayAreaInfo();
			jpayAreaQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			jpayAreaQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.jpayService.queryAreaPage(jpayAreaQuery,
					getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}
		return "area_list";
	}

	public String areaSync() throws Exception {
		try {
			this.jpayService.areaSync(gameId, getCurrentOperator());
			this.redirectionUrl = "jpay!areaList.htm";
		} catch (ManagerException e) {
			flag = false;
			this.addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 编辑
	 * 
	 * @return
	 * @throws Exception
	 */
	public String toEdit() throws Exception {
		try {
			jpayGoodsInfo = this.jpayService
					.queryById(id, getCurrentOperator());
		} catch (ManagerException e) {
			this.addActionError(e.getMessage());
		}

		return INPUT;
	}

	/**
	 * 修改
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception {
		try {
			this.jpayService.updateGoods(jpayGoodsInfo, getCurrentOperator());

			if (jpayGoodsQuery == null) {
				jpayGoodsQuery = new JpayGoodsInfo();
				jpayGoodsQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
				jpayGoodsQuery.setPageSize(Constants.INIT_PAGESIZE);
			}
			if (StringUtils.isNotEmpty(goodsId)) {
				jpayGoodsQuery.setGoodsId(goodsId);
			}
			if (StringUtils.isNotEmpty(goodsName)) {
				jpayGoodsQuery.setGoodsName(goodsName);
			}
		} catch (Exception e) {
			this.addActionError(e.getMessage());
		}

		return list();
	}

	/**
	 * 商品审核
	 * 
	 * @return
	 * @throws Exception
	 */
	public String audit() throws Exception {
		try {
			this.jpayService.confirmAudit(supplierId, priceRatio,
					getCurrentOperator());
			redirectionUrl = "jpay!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 批量上架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOnline() throws Exception {
		try {
			this.jpayService.batchOnOffline("1", getCurrentOperator());
			redirectionUrl = "jpay!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 批量下架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOffline() throws Exception {
		try {
			this.jpayService.batchOnOffline("0", getCurrentOperator());
			redirectionUrl = "jpay!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	public String toOrderQuery() {
		return "order_query";
	}

	/**
	 * 订单查询
	 * 
	 * @return
	 * @throws Exception
	 */
	public String orderQuery() throws Exception {
		try {
			orderInfo = this.jpayService.orderQuery(userid, requestid, history,
					getCurrentOperator());
			orderInfo.setHistory(history);
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return "order_query";
	}

	public String toBalanceQuery() {
		return "balance_query";
	}

	/**
	 * 余额查询
	 * 
	 * @return
	 * @throws Exception
	 */
	public String balanceQuery() throws Exception {
		try {
			balanceInfo = this.jpayService.balanceQuery(userid,
					getCurrentOperator());

		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return "balance_query";
	}

	/**
	 * 导入产品excel文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String importProductFile() throws Exception {
		if (StringUtils.isEmpty(productExcelFileName)) {
			flag = false;
			addActionError("请选择要导入的文件!");
			return SUCCESS;
		}
		if (!productExcelFileName.endsWith(".xls")
				&& !productExcelFileName.endsWith(".xlsx")) {
			flag = false;
			addActionError("文件类型有误!<br>必须为excel文件!");
			return SUCCESS;
		}
		InputStream is = null;
		try {
			is = new FileInputStream(productExcel);
		} catch (FileNotFoundException e1) {
			addActionError(e1.getMessage());
		}
		List<JpayGoodsInfo> list = null;
		try {
			if (is != null) {
				if (productExcelFileName.endsWith(".xls")) {
					list = this.extractListFromXLS2003(is);
				} else if (productExcelFileName.endsWith(".xlsx")) {
					list = this.extractListFromXLS2007(is);
				}
			}
		} catch (IOException e) {
			addActionError(e.getMessage());
		}
		String message = "";
		if (list != null && !list.isEmpty()) {
			for (JpayGoodsInfo jInfo : list) {
				if (jInfo != null) {
					try {
						jInfo.setRechargeType("2");
						this.jpayService.saveGoods(jInfo, getCurrentOperator());
					} catch (ManagerException e) {
						message += jInfo.getGoodsId() + "," + e.getMessage()
								+ "<br>";
						continue;
					}
				}
			}
		}
		if (StringUtils.isNotEmpty(message)) {
			flag = false;
			addActionError(message);
		}
		this.redirectionUrl = "jpay!list.htm";
		return SUCCESS;
	}

	/**
	 * 解析excel2003文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private List<JpayGoodsInfo> extractListFromXLS2003(InputStream is)
			throws IOException {
		List<JpayGoodsInfo> list = new ArrayList<JpayGoodsInfo>();
		JpayGoodsInfo jInfo = null;
		HSSFWorkbook workbook = new HSSFWorkbook(is); // 创建对Excel工作簿文件的引用
		for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
			if (null != workbook.getSheetAt(numSheets)) {
				HSSFSheet aSheet = workbook.getSheetAt(numSheets); // 获得一个sheet
				for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet
						.getLastRowNum(); rowNumOfSheet++) {
					if (null != aSheet.getRow(rowNumOfSheet)) {
						jInfo = new JpayGoodsInfo();
						List<String> cellList = new ArrayList<String>();
						HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一行
						for (int cellNumOfRow = 0; cellNumOfRow <= aRow
								.getLastCellNum(); cellNumOfRow++) {
							if (null != aRow.getCell(cellNumOfRow)) {
								HSSFCell aCell = aRow.getCell(cellNumOfRow); // 获得列值
								if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
									double parvalue = aCell
											.getNumericCellValue();
									cellList.add(String.valueOf(parvalue));
								} else if (aCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
									boolean flag = aCell.getBooleanCellValue();
									cellList.add(String.valueOf(flag));
								} else {
									cellList.add(aCell.getStringCellValue());
								}
								if (cellList.size() > 0) {
									jInfo.setGoodsId(cellList.get(0));
								}
								if (cellList.size() > 1) {
									jInfo.setParValue(cellList.get(1));
								}
								if (cellList.size() > 2) {
									String parvalue = cellList.get(1);
									parvalue = parvalue.substring(0,
											parvalue.indexOf("."));
									jInfo.setGoodsName(cellList.get(2) + "-"
											+ parvalue + "元直充");
								}
								if (cellList.size() > 3) {
									jInfo.setInPrice(cellList.get(3));
								}
								if (cellList.size() > 4) {
									jInfo.setRemark(cellList.get(4));
								}
							}
						}

					}
					list.add(jInfo);
				}
			}
		}
		return list;
	}

	/**
	 * 解析excel2007文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	private List<JpayGoodsInfo> extractListFromXLS2007(InputStream is)
			throws IOException {
		List<JpayGoodsInfo> list = new ArrayList<JpayGoodsInfo>();
		JpayGoodsInfo jInfo = null;
		// 构造 XSSFWorkbook 对象，strPath
		// 传入文件路径
		XSSFWorkbook xwb = new XSSFWorkbook(is);
		// 循环工作表Sheet
		for (int numSheet = 0; numSheet < xwb.getNumberOfSheets(); numSheet++) {
			XSSFSheet xSheet = xwb.getSheetAt(numSheet);
			if (xSheet == null) {
				continue;
			}
			// 循环行Row
			for (int rowNum = 1; rowNum <= xSheet.getLastRowNum(); rowNum++) {
				jInfo = new JpayGoodsInfo();
				XSSFRow xRow = xSheet.getRow(rowNum);
				if (xRow == null) {
					continue;
				}
				List<String> cellList = new ArrayList<String>();
				// 循环列Cell
				for (int cellNum = 0; cellNum <= xRow.getLastCellNum(); cellNum++) {
					XSSFCell xCell = xRow.getCell(cellNum);

					if (xCell == null) {
						continue;
					}
					if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
						boolean flag = xCell.getBooleanCellValue();
						cellList.add(String.valueOf(flag));
					} else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
						double parvalue = xCell.getNumericCellValue();
						cellList.add(String.valueOf(parvalue));
					} else {
						cellList.add(xCell.getStringCellValue());
					}
					if (cellList.size() > 0) {
						jInfo.setGoodsId(cellList.get(0));
					}
					if (cellList.size() > 1) {
						jInfo.setParValue(cellList.get(1));
					}
					if (cellList.size() > 2) {
						String parvalue = cellList.get(1);
						parvalue = parvalue.substring(0, parvalue.indexOf("."));
						jInfo.setGoodsName(cellList.get(2) + "-" + parvalue
								+ "元直充");
					}
					if (cellList.size() > 3) {
						jInfo.setInPrice(cellList.get(3));
					}
					if (cellList.size() > 4) {
						jInfo.setRemark(cellList.get(4));
					}
				}
				list.add(jInfo);
			}
		}
		return list;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public JpayGoodsInfo getJpayGoodsInfo() {
		return jpayGoodsInfo;
	}

	public void setJpayGoodsInfo(JpayGoodsInfo jpayGoodsInfo) {
		this.jpayGoodsInfo = jpayGoodsInfo;
	}

	public JpayAreaInfo getJpayAreaInfo() {
		return jpayAreaInfo;
	}

	public void setJpayAreaInfo(JpayAreaInfo jpayAreaInfo) {
		this.jpayAreaInfo = jpayAreaInfo;
	}

	public JpayGoodsInfo getJpayGoodsQuery() {
		return jpayGoodsQuery;
	}

	public void setJpayGoodsQuery(JpayGoodsInfo jpayGoodsQuery) {
		this.jpayGoodsQuery = jpayGoodsQuery;
	}

	public JpayAreaInfo getJpayAreaQuery() {
		return jpayAreaQuery;
	}

	public void setJpayAreaQuery(JpayAreaInfo jpayAreaQuery) {
		this.jpayAreaQuery = jpayAreaQuery;
	}

	public String getGoodsId() {
		return goodsId;
	}

	public void setGoodsId(String goodsId) {
		this.goodsId = goodsId;
	}

	public String getGoodsName() {
		return goodsName;
	}

	public void setGoodsName(String goodsName) {
		this.goodsName = goodsName;
	}

	public String getSupplierId() {
		return supplierId;
	}

	public void setSupplierId(String supplierId) {
		this.supplierId = supplierId;
	}

	public int getPriceRatio() {
		return priceRatio;
	}

	public void setPriceRatio(int priceRatio) {
		this.priceRatio = priceRatio;
	}

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getRequestid() {
		return requestid;
	}

	public void setRequestid(String requestid) {
		this.requestid = requestid;
	}

	public String getHistory() {
		return history;
	}

	public void setHistory(String history) {
		this.history = history;
	}

	public JpayGoodsInfo getOrderInfo() {
		return orderInfo;
	}

	public void setOrderInfo(JpayGoodsInfo orderInfo) {
		this.orderInfo = orderInfo;
	}

	public JpayGoodsInfo getBalanceInfo() {
		return balanceInfo;
	}

	public void setBalanceInfo(JpayGoodsInfo balanceInfo) {
		this.balanceInfo = balanceInfo;
	}

	public File getProductExcel() {
		return productExcel;
	}

	public void setProductExcel(File productExcel) {
		this.productExcel = productExcel;
	}

	public String getProductExcelFileName() {
		return productExcelFileName;
	}

	public void setProductExcelFileName(String productExcelFileName) {
		this.productExcelFileName = productExcelFileName;
	}

	public String getProductExcelContentType() {
		return productExcelContentType;
	}

	public void setProductExcelContentType(String productExcelContentType) {
		this.productExcelContentType = productExcelContentType;
	}

	public String getGameId() {
		return gameId;
	}

	public void setGameId(String gameId) {
		this.gameId = gameId;
	}

}
